﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
using System.Drawing;

namespace Common
{
    public enum EventType
    {
        Information,
        Error,
        Success
    }
	public class  RichTextBoxTraceListener  
	{
		#region Readonly & Static Fields

        private readonly Dictionary<EventType, Color> m_EventColor =
            new Dictionary<EventType, Color>();

		#endregion

		#region Constructors
        RichTextBox m_richTextBox;
        public RichTextBoxTraceListener(RichTextBox richtextbox)
		{
            m_EventColor.Add(EventType.Information, Color.Black);
            m_EventColor.Add(EventType.Error, Color.Red);
            m_EventColor.Add(EventType.Success, Color.Green);
            m_richTextBox = richtextbox;
		}

		#endregion

		#region Instance Methods

        public void TraceEvent(EventType eventType, string message)
		{
			TraceEvent(eventType, "{0}", message);
		}

        public void TraceEvent(EventType eventType,string format, params object[] args)
        {
            lock (m_richTextBox)
            {
                m_richTextBox.Invoke((MethodInvoker)delegate
                 {
                     Color originalColor = m_richTextBox.SelectionColor;
                     m_richTextBox.SelectionColor = GetEventColor(eventType, originalColor);
                     m_richTextBox.AppendText(string.Format(format, args) + "\r\n");
                     m_richTextBox.SelectionColor = originalColor;
                 });
            }
		}

        private Color GetEventColor(EventType eventType, Color defaultColor)
		{
			return !m_EventColor.ContainsKey(eventType) ? defaultColor : m_EventColor[eventType];
		}

		#endregion
	}
}